﻿using System;
using System.Threading;

namespace 用户模式互锁结构之Interlocked
{
    class Program
    {
        static void Main(string[] args)
        {

            int n = 0;
            Console.WriteLine($"给{n}每次+1 加10次");
            for (int i = 0; i < 10; i++)
            {
                Interlocked.Increment(ref n);
            }
            Console.WriteLine($"加后的值{n}");
            Console.WriteLine($"开始减10次");
            for (int i = 0; i < 10; i++)
            {
                Interlocked.Decrement(ref n);
            }
            Console.WriteLine($"减后的值{n}");
            Console.WriteLine($"每次加5");
            for (int i = 0; i < 10; i++)
            {
                Interlocked.Add(ref n,5);
            }
            Console.WriteLine($"每次加5后的值{n}");
            Console.WriteLine("================");
            Interlocked.Exchange(ref n,15);
            Console.WriteLine($"交换值后{n}");

            Console.WriteLine("=========================");
            int n0 = 7;
            var n1 = 12;
            var n2 = 10;
            //n1与 n2 比较，if  相等，n0替换n1，不相等，什么都不做
            Interlocked.CompareExchange(ref n1, n0, n2);
            Console.WriteLine(n1);

            Console.Read(); 
        }
    }
}
